package cn.ad.server.web.spring.service.actions.context;

import cn.ad.server.common.utils.BrowserUtils;
import cn.ad.server.common.utils.IPUtils;
import cn.ad.server.common.utils.StringUtil;
import cn.ad.server.domain.enumration.*;
import cn.ad.server.web.spring.model.BidAdRequest;
import cn.ad.server.web.spring.model.Exchange;
import cn.ad.server.web.spring.model.adview.*;
import cn.ad.server.web.spring.model.sts.STSAdRequest;
import cn.ad.server.domain.IPDetail;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 广告请求上下文工厂方法构造类
 * 
 * @author dongbin.yu
 * @from 2016-05-19
 * @since V1.0
 */
@Deprecated
public class AdContextBuilder {

	private STSAdRequest adRequest;

	private HttpServletRequest request;

	public AdContextBuilder(STSAdRequest adRequest, HttpServletRequest request) {
		this.adRequest = adRequest;
		this.request = request;
	}

	/**
	 * 创建Server to Server 广告请求上下文
	 * 
	 * @param adRequest
	 * @return
	 */
	public static AdContext build(STSAdRequest adRequest) {
		AdContext adContext = new AdContext();
		adContext.setRequestTimestamp(System.currentTimeMillis());
		adContext.setVersion(adRequest.getVersion());

		adContext.setServerId(IPUtils.getHostName());

		// 设置设备信息
		STSAdRequest.Device device = adRequest.getDevice();

		// 解析ip
		adContext.setIp(device.getIp());
		// 此处IP设置代码移动到Servlet中处理
		// adContext.setRequestIp(IPUtils.parseIp(request));

		boolean init = true;

		if (StringUtils.hasText(device.getMac()) || StringUtils.hasText(device.getMacori())) {
			adContext.setMac(device.getMac());
			adContext.setMacori(device.getMacori());
			if (init) {
				adContext.setMuniqueType(MUniqueType.MAC.getValue());
				adContext.setMuniqueId(device.getMac());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getMac1())) {
			adContext.setMac1(device.getMac1());
			if (init) {
				adContext.setMuniqueType(MUniqueType.MAC1.getValue());
				adContext.setMuniqueId(device.getMac1());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getImei()) || StringUtils.hasText(device.getImeiori())) {
			adContext.setImei(device.getImei());
			adContext.setImeiori(device.getImeiori());
			if (init) {
				adContext.setMuniqueType(MUniqueType.IMEI.getValue());
				adContext.setMuniqueId(device.getImei());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getIdfa()) || StringUtils.hasText(device.getIdfaori())) {
			adContext.setIdfa(device.getIdfa());
			adContext.setIdfaori(device.getIdfaori());
			if (init) {
				adContext.setMuniqueType(MUniqueType.IDFA.getValue());
				adContext.setMuniqueId(device.getIdfa());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getDuid())) {
			adContext.setDuid(device.getDuid());
			if (init) {
				adContext.setMuniqueType(MUniqueType.DUID.getValue());
				adContext.setMuniqueId(device.getDuid());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getAnid()) || StringUtils.hasText(device.getAnidori())) {
			adContext.setAndroidId(device.getAnid());
			adContext.setAnidori(device.getAnidori());
			if (init) {
				adContext.setMuniqueType(MUniqueType.ANDROIDID.getValue());
				adContext.setMuniqueId(device.getAnid());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getUdid())) {
			adContext.setUdid(device.getUdid());
			if (init) {
				adContext.setMuniqueType(MUniqueType.UDID.getValue());
				adContext.setMuniqueId(device.getUdid());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getAaid())) {
			adContext.setAaid(device.getAaid());
			if (init) {
				adContext.setMuniqueType(MUniqueType.AAID.getValue());
				adContext.setMuniqueId(device.getAaid());
				init = false;
			}
		}

		adContext.setMob_ops(device.getOperator());
		adContext.setBrand(device.getBrand());
		adContext.setModel(device.getPlatform());
		adContext.setOs(device.getOs());
		adContext.setOsVersion(device.getOsVersion());
		adContext.setConnType(device.getNetwork());
		String deviceSize = device.getDeviceSize();
		if (deviceSize != null && deviceSize.contains("*")) {

			String[] size = deviceSize.split("\\*");
			adContext.setScreenWidth(Integer.parseInt(size[0]));
			adContext.setScreenHeight(Integer.parseInt(size[1]));
		}
		adContext.setScreenOritent(device.getScreenOrientation());
		adContext.setLatitude(device.getLatitude());
		adContext.setLongitude(device.getLongitude());

		// 城市解析
		IPDetail ipDetail = IPContext.instance().getIPDetail(IPUtils.convertIPToLong(adContext.getIp()));
		if (ipDetail != null) {
			adContext.setCountryId(ipDetail.getCountryId());
			adContext.setStateId(ipDetail.getStateId());
			adContext.setCityId(ipDetail.getCityId());
			adContext.setAreaId(ipDetail.getDistrictId());
		}

		return adContext;
	}

	/**
	 * 创建BID请求上下文实例
	 * 
	 * @return
	 */
	public static BidContext build(BidAdRequest bidAdRequest) {

		BidContext bidContext = new BidContext();
		if (bidAdRequest == null)
			return null;
		bidContext.setChannel(bidAdRequest.getChannelID());
		bidContext.setAdxType(Integer.parseInt(Exchange.ADVIEW.getValue()));
		bidContext.setRequestTimestamp(System.currentTimeMillis());
		bidContext.setServerId(IPUtils.getHostName());

		AdViewBidRequest adViewBidRequest = (AdViewBidRequest) bidAdRequest;
		bidContext.setFeeType(StringUtils.arrayToCommaDelimitedString(adViewBidRequest.getCur()));
		bidContext.setTransactionType(adViewBidRequest.getAt().ordinal());
		bidContext.setBidId(adViewBidRequest.getId());

		// Device信息
		Device device = adViewBidRequest.getDevice();
		if (device != null) {

			bidContext.setDnt(device.getDnt());
			bidContext.setUa(device.getUa());
			bidContext.setIp(device.getIp());
			// 城市解析
			IPDetail ipDetail = IPContext.instance().getIPDetail(IPUtils.convertIPToLong(bidContext.getIp()));
			if (ipDetail != null) {
				bidContext.setCountryId(ipDetail.getCountryId());
				bidContext.setStateId(ipDetail.getStateId());
				bidContext.setCityId(ipDetail.getCityId());
				bidContext.setDistrictId(ipDetail.getDistrictId());
			}
			bidContext.setIdfa(device.getIdfa());
			bidContext.setImeisha1(device.getDidsha1());
			bidContext.setDpidsha1(device.getDpidsha1());
			bidContext.setMacsha1(device.getMacsha1());
			bidContext.setImeimd5(device.getDidmd5());
			bidContext.setDpidmd5(device.getDpidmd5());
			bidContext.setLanguage(device.getLanguage());
			bidContext.setBrand(device.getMake());
			bidContext.setModal(device.getModel());

			boolean init = true;

			if (StringUtils.hasText(device.getMacmd5())) {
				bidContext.setMacmd5(device.getMacmd5());
				if (init) {
					bidContext.setMuniqueType(MUniqueType.MAC.getValue());
					bidContext.setMuniqueId(device.getMacmd5());
					init = false;
				}
			}

			if (StringUtils.hasText(device.getMacsha1())) {
				bidContext.setMacsha1(device.getMacsha1());
				if (init) {
					bidContext.setMuniqueType(MUniqueType.MAC.getValue());
					bidContext.setMuniqueId(device.getMacsha1());
					init = false;
				}
			}

			if (StringUtils.hasText(device.getDidmd5())) {
				bidContext.setImeimd5(device.getDidmd5());
				if (init) {
					bidContext.setMuniqueType(MUniqueType.IMEI.getValue());
					bidContext.setMuniqueId(device.getDidmd5());
					init = false;
				}
			}

			if (StringUtils.hasText(device.getDidsha1())) {
				bidContext.setImeisha1(device.getDidsha1());
				if (init) {
					bidContext.setMuniqueType(MUniqueType.IMEI.getValue());
					bidContext.setMuniqueId(device.getDidsha1());
					init = false;
				}
			}

			if (StringUtils.hasText(device.getIdfa())) {
				bidContext.setIdfa(device.getIdfa());
				if (init) {
					bidContext.setMuniqueType(MUniqueType.IDFA.getValue());
					bidContext.setMuniqueId(device.getIdfa());
					init = false;
				}
			}

			// 操作系统
			String os = device.getOs();
			if (os != null) {
				if (os.toLowerCase().contains("ios")) {
					bidContext.setOs(OS.IOS.getValue());
				} else if (os.toLowerCase().contains("android")) {
					bidContext.setOs(OS.ANDROID.getValue());
				} else if (os.toLowerCase().contains("windows")) {
					bidContext.setOs(OS.WINDOWS.getValue());
				} else {
					bidContext.setOs(OS.UNKNOWN.getValue());
				}
			}

			bidContext.setOsVersion(device.getOsv());
			bidContext.setJsEnable(device.getJs());
			Connection connection = AdViewConnection.adViewConnectionMap.get(device.getConnectiontype());
			if (connection != null) {
				bidContext.setConnType(connection.getValue());
			}
			if(device.getDevicetype() != null)
				bidContext.setDeviceType(device.getDevicetype().ordinal());
			bidContext.setScreenDensity(device.getS_density());
			bidContext.setScreenWidth(device.getSw());
			bidContext.setScreenHeight(device.getSh());
			bidContext.setScreenOritent(device.getOrientation());
			Operator operator = AdViewOperator.adViewOperatorMap.get(device.getCarrier());
			if (operator != null) {
				bidContext.setMobOps(operator.getValue());
			}
			Geo geo = device.getGeo();
			if (geo != null) {
				bidContext.setLatitude(geo.getLat());
				bidContext.setLongitude(geo.getLon());
			}
		}

		App app = adViewBidRequest.getApp();
		if (app != null) {
			bidContext.setAppId(app.getId());
			bidContext.setAppName(app.getName());
			// FIXME 需要做类型转换
			bidContext.setAppType(StringUtil.arrayToCommaDelimitedString(app.getCat()));
			bidContext.setAppDomain(app.getDomain());
			bidContext.setAppVersion(app.getVer());
			bidContext.setAppBundle(app.getBundle());
			bidContext.setAppStoreUrl(app.getStoreurl());
			bidContext.setAppKeywords(app.getKeywords());
			bidContext.setAppIsPay(app.getPaid());
		}

		bidContext.setBrowser(BrowserUtils.getBrowser(bidContext.getUa()));
		User user = adViewBidRequest.getUser();
		if (user != null) {
			bidContext.setUserId(user.getId());
			// 用户性别
			String gender = user.getGender();
			if ("M".equals(gender)) {
				bidContext.setGender(Gender.MALE.getValue());
			} else if ("F".equals(gender)) {
				bidContext.setGender(Gender.FEMALE.getValue());
			} else {
				bidContext.setGender(Gender.UNKNOWN.getValue());
			}
			bidContext.setInteresting(user.getKeywords());
			bidContext.setAgeLow(user.getAge_low());
			bidContext.setAgeHigh(user.getAge_high());
		}

		bidContext.setIncludeAdvertiser(StringUtils.arrayToCommaDelimitedString(adViewBidRequest.getWeat()));
		bidContext.setExcludeIndustryCategory(StringUtils.arrayToCommaDelimitedString(adViewBidRequest.getBcat()));
		bidContext.setExcludeAdvertiserDomain(StringUtils.arrayToCommaDelimitedString(adViewBidRequest.getBadv()));

		return bidContext;
	}

	/**
	 * 解析 在Adserver2.0 版本后将采用静态方法构造，不推荐此方法，
	 */
	@Deprecated
	public void buildAdContext() {
		AdContext adContext = new AdContext();
		adContext.setRequestTimestamp(System.currentTimeMillis());
		adContext.setVersion(adRequest.getVersion());

		adContext.setServerId(IPUtils.getHostName());

		// 设置设备信息
		STSAdRequest.Device device = adRequest.getDevice();

		// 解析ip
		adContext.setIp(device.getIp());
		adContext.setReferer(request.getHeader("Referer"));
		adContext.setRequestIp(IPUtils.parseIp(request));

		boolean init = true;

		if (StringUtils.hasText(device.getMac()) || StringUtils.hasText(device.getMacori())) {
			adContext.setMac(device.getMac());
			adContext.setMacori(device.getMacori());
			if (init) {
				adContext.setMuniqueType(MUniqueType.MAC.getValue());
				adContext.setMuniqueId(device.getMac());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getMac1())) {
			adContext.setMac1(device.getMac1());
			if (init) {
				adContext.setMuniqueType(MUniqueType.MAC1.getValue());
				adContext.setMuniqueId(device.getMac1());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getImei()) || StringUtils.hasText(device.getImeiori())) {
			adContext.setImei(device.getImei());
			adContext.setImeiori(device.getImeiori());
			if (init) {
				adContext.setMuniqueType(MUniqueType.IMEI.getValue());
				adContext.setMuniqueId(device.getImei());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getIdfa()) || StringUtils.hasText(device.getIdfaori())) {
			adContext.setIdfa(device.getIdfa());
			adContext.setIdfaori(device.getIdfaori());
			if (init) {
				adContext.setMuniqueType(MUniqueType.IDFA.getValue());
				adContext.setMuniqueId(device.getIdfa());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getDuid())) {
			adContext.setDuid(device.getDuid());
			if (init) {
				adContext.setMuniqueType(MUniqueType.DUID.getValue());
				adContext.setMuniqueId(device.getDuid());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getAnid()) || StringUtils.hasText(device.getAnidori())) {
			adContext.setAndroidId(device.getAnid());
			adContext.setAnidori(device.getAnidori());
			if (init) {
				adContext.setMuniqueType(MUniqueType.ANDROIDID.getValue());
				adContext.setMuniqueId(device.getAnid());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getUdid())) {
			adContext.setUdid(device.getUdid());
			if (init) {
				adContext.setMuniqueType(MUniqueType.UDID.getValue());
				adContext.setMuniqueId(device.getUdid());
				init = false;
			}
		}

		if (StringUtils.hasText(device.getAaid())) {
			adContext.setAaid(device.getAaid());
			if (init) {
				adContext.setMuniqueType(MUniqueType.AAID.getValue());
				adContext.setMuniqueId(device.getAaid());
				init = false;
			}
		}

		adContext.setMob_ops(device.getOperator());
		adContext.setBrand(device.getBrand());
		adContext.setModel(device.getPlatform());
		adContext.setOs(device.getOs());
		adContext.setOsVersion(device.getOsVersion());
		adContext.setConnType(device.getNetwork());
		String deviceSize = device.getDeviceSize();
		if (deviceSize != null && deviceSize.contains("*")) {

			String[] size = deviceSize.split("\\*");
			adContext.setScreenWidth(Integer.parseInt(size[0]));
			adContext.setScreenHeight(Integer.parseInt(size[1]));
		}
		adContext.setScreenOritent(device.getScreenOrientation());
		adContext.setLatitude(device.getLatitude());
		adContext.setLongitude(device.getLongitude());

		// 城市解析
		IPDetail ipDetail = IPContext.instance().getIPDetail(IPUtils.convertIPToLong(adContext.getIp()));
		if (ipDetail != null) {
			adContext.setCountryId(ipDetail.getCountryId());
			adContext.setStateId(ipDetail.getStateId());
			adContext.setCityId(ipDetail.getCityId());
			adContext.setAreaId(ipDetail.getDistrictId());
		}

		// 浏览器解析
		String ua = request.getHeader("user-agent");
		String browser = BrowserUtils.getBrowser(ua);
		adContext.setBrowser(browser);
		adContext.setUa(ua);
		adContext.setIp(device.getIp());
		adContext.setReferer(request.getHeader("Referer"));

		adRequest.setAdContext(adContext);

	}

}
